package com.example.demo.util;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by chenkai on 15/3/9.
 * 计算摘要工具
 */
public class DigestUtil {

    public static String fileMD5(File file) {
        String md5str = "";
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("MD5");
            FileInputStream in = new FileInputStream(file);
            FileChannel fc = in.getChannel();
            MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            messageDigest.update(byteBuffer);
            md5str = ISOUtils.hexString(messageDigest.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return md5str;
    }

    public static String md5(byte[] data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(data);
            byte[] resultBytes = md.digest();
            return ISOUtils.hexString(resultBytes);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("caculate digest error!", e);
        }
    }


    public static String encodeHmacSHA(String data, byte[] key) {
        // 还原密钥
        SecretKey secretKey = new SecretKeySpec(key, "HMacSHA1");
        System.out.println("还原密钥算法：" + secretKey.getAlgorithm());
        System.out.println("还原秘钥：" + new String(secretKey.getEncoded()));
        // 实例化Mac
        Mac mac = null;
        // 初始化Mac
        try {
            mac = Mac.getInstance(secretKey.getAlgorithm());
            mac.init(secretKey);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
        // 执行消息摘要
        return ISOUtils.hexString(mac.doFinal(data.getBytes()));
    }

/*    public static String calculateToken(ReqHead reqHead,String rettime){
        String token = encodeHmacSHA(reqHead.getTermid()+reqHead.getFid()+reqHead.getMid()
                        +rettime+reqHead.getBusid(),
                MtmsService.HMAC_KEY.getBytes());
        System.out.println("原数据："+reqHead.getTermid()+reqHead.getFid()+reqHead.getMid()
                +rettime+reqHead.getBusid());
        System.out.println("摘要数据："+token);
        return token;
    }*/
}
